import time
import platform
import setproctitle
import multiprocessing
from threading import Thread

from basic.config import GlobalInfo, GlobalCfg
from modules.module import Module
from modules.sigalarm.sigalarm import Sigalarm
from modules.base64.base64 import Base64
from modules.knowledgelib.knowledgelib import KnowledgeLib
from modules.giteeID.giteeID import GiteeID
from modules.segment_calculator.segment_calculator import SegmentCalculator
from modules.zbfindhuman.zbfindhuman import ZbFindHuman
from modules.sqlvisualization.sqlvisualization import SqlVisualization


class ModuleMaster(Module):
    @staticmethod
    def independent_run(module):
        """
        启动一个进程或线程来运行module
        """
        if GlobalInfo.is_multi_process_mode:
            p = multiprocessing.Process(target=module.run)
            p.start()
            return p
        else:
            t = Thread(target=module.run)
            t.start()
            return t

    def __init__(self):
        super(ModuleMaster, self).__init__(None, 'module_master')
        self.independent = True
        self.common_modules = [

        ]
        self.website_modules = [
            Sigalarm(self),
            Base64(self),
            # KnowledgeLib(self),
            # GiteeID(self),
            SegmentCalculator(self),
            ZbFindHuman(self),
            SqlVisualization(self)
        ]

        self._process = None
        self._subprocess = {}

    def power_on(self):
        self._process = ModuleMaster.independent_run(self)

    def run(self):
        self.runlog.log('module master 启动运行')
        self.setproctitle("[devkit service process] - module master")

        is_first_run = True
        while True:
            for m in self.common_modules + self.website_modules:
                if not m.enable():
                    self.runlog.log(f'未配置启动 {m.name}')
                    continue
                
                if not m.independent:
                    if is_first_run:
                        self.runlog.log(f'执行 {m.name} 初始化')
                        m.run()
                    else:
                        self.runlog.log(f'{m.name} 状态正常。')
                    continue
                
                p = self._subprocess.get(m.name)
                if p is not None:
                    if p.is_alive():
                        self.runlog.log(f'{m.name} 运行正常。')
                        continue
                    else:
                        self.runlog.log(f'{m.name} 异常退出，{p.exitcode}。')

                self.runlog.log(f'拉起 {m.name} 进程')
                newp = ModuleMaster.independent_run(m)
                self._subprocess[m.name] = newp

            is_first_run = False
            time.sleep(300)

